<template>
  <!-- 供方退货修改 -->
  <div class="e-form">
    <div class="tabs" v-if="Object.keys(basicFormData).length != 0">
      <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
        <!-- 基本信息 -->
        <el-tab-pane
          label="基本信息"
          name="baseInfo"
          :disabled="clickTabFlag"
        ></el-tab-pane>
        <el-tab-pane
          label="退货明细"
          name="receivingMaterials"
          :disabled="clickTabFlag"
        ></el-tab-pane>

        <el-tab-pane
          label="附件信息"
          name="accessory"
          :disabled="clickTabFlag"
        ></el-tab-pane>
        <el-tab-pane
          label="审核历史"
          name="auditHistory"
          :disabled="clickTabFlag"
        ></el-tab-pane>

        <div>
          <!-- 基本信息 -->
          <div id="baseInfoCon" class="con">
            <div class="e-form">
                <BillTop title="供方退货编辑" @cancel="cancel"></BillTop>
              <div class="tabs">
                <div class="tabs-title" id="baseInfo">基本信息</div>
                <div style="width: 100%" class="form">
                  <el-form :model="basicFormData" label-width="150px"    ref="ruleForm"
                    :rules="rules"
                    class="demo-ruleForm">
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="退货编号">
                          {{basicFormData.billNo}}
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="所属机构">
                          {{ basicFormData.orgName }}
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="供应商">
                          <el-input
                            disabled
                            v-model="basicFormData.supplierName"
                          ></el-input>
                          <el-button  type="primary" style="background: #2e61d7;margin-left:5px" @click="selectMaterial()">选择库存</el-button>
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="退货日期" prop="returnDate">
                          <el-date-picker
                            v-model="basicFormData.returnDate"
                            value-format="yyyy-MM-dd"
                            type="date"
                            placeholder="选择日期"
                            :clearable="false"
                          >
                          </el-date-picker>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="退货数量">
                          <!-- 汇总退货明细中所有物资的本次退货数量 -->
                          {{basicFormData.returnQuantity}}
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="接收人员" prop="receivingPersonnelName">
                          <el-select
                            v-model="basicFormData.receivingPersonnelName"
                            placeholder="请选择"

                          >
                            <el-option
                              v-for="item in userList"
                              :key="item.userId"
                              :label="item.userName"
                              :value="item.userName"
                            >
                            </el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="收料数量">
                          {{basicFormData.receivedQuantity}}
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="库管人员" prop="warehouseKeeperName">
                            <el-select
                              v-model="basicFormData.warehouseKeeperName"
                              placeholder="请选择"
                            >
                              <el-option
                                v-for="item in userLists"
                                :key="item.userId"
                                :label="item.userName"
                                :value="item.userName"
                              >
                              </el-option>
                            </el-select>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="截止上期退货数量">
                          {{basicFormData.previousTotalReturnQuantity}}
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="状态">
                          {{
                          ["草稿", "审核中", "已审核", "已关闭",'', "已作废"][
                            basicFormData.state
                          ]
                        }}
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="截止本期退货数量">
                          {{basicFormData.currentTotalReturnQuantity}}
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="评价等级" prop="evaluationLevel" v-if="iswuzi">
                          <el-input
                            disabled
                            v-model="basicFormData.evaluationLevel"
                          ></el-input>
                          <el-button  type="primary" style="background: #2e61d7;margin-left:5px" @click="evaluate">退货评价</el-button>
                        </el-form-item>
                         <el-form-item label="评价等级" v-else>
                          <el-input
                            disabled
                            v-model="basicFormData.evaluationLevel"
                          ></el-input>
                          <el-button  type="primary" style="background: #2e61d7;margin-left:5px" @click="evaluate">退货评价</el-button>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-form-item label="备注">
                        <el-input
                          type="textarea"
                          :rows="2"
                          placeholder="请输入内容"
                          v-model="basicFormData.remarks"
                        >
                        </el-input>
                      </el-form-item>
                    </el-row>

                  </el-form>
                </div>
              </div>
            </div>
          </div>

          <!-- 退货明细 -->
          <div id="receivingMaterialsCon" class="con">
            <div class="tabs-title" id="receivingMaterials">退货明细</div>
            <div class="e-table">
              <div class="top">
                <div class="left">
                  <div>
                    <el-button
                      size="small"
                      style="background: rgb(75, 178, 255); color: #fff"
                      class="btn-blue"
                       @click="selectMaterial()"
                      >选择库存</el-button
                    >
                  </div>
                </div>
              </div>
                <div class="errorMsg" v-if="errorMsg.length > 0">
                    <span v-for="(item, index) in errorMsg" :key="index">
                    {{ item }}
                    </span>
                </div>
              <el-table
                :data="receivingList"
                border
                style="width: 100%"
                 :row-class-name="tableRowClassName"
                :cell-class-name="cellClsNm"
                :header-cell-style="{ textAlign: 'center' }"
                :cell-style="{ textAlign: 'center' }"
                   :tree-props="{
                  children: 'children',
                  hasChildren: 'hasChildren',
                }"
                row-key="uuid"
                :max-height="$store.state.tableHeight"
                 ref="table"
                v-sortTable="{ 'tableData': receivingList, '_this': this, 'ref': 'table' }"
              >
                <el-table-column
                  label="操作"
                  fixed
                  width="100px"
                  align="left"
                  v-if="isBatch"
                >
                  <template slot-scope="{ row, $index }">
                    <i
                      class="el-icon-delete"
                      style="cursor: pointer; font-size: 20px; color: red"

                      @click="deleteEle(row)"
                      v-if="$index > 0&& row.billId"
                    ></i>
                  </template>
                </el-table-column>
                <el-table-column prop="materialClassName" label="物资类别" min-width="200">
                </el-table-column>
                <el-table-column prop="materialName" label="物资名称" min-width="200">
                </el-table-column>
                <el-table-column prop="spec" label="规格" min-width="200">
                </el-table-column>
                  <el-table-column prop="texture" label="材质" min-width="200">
                </el-table-column>
                <el-table-column prop="warehouseName" label="仓库" min-width="200">
                </el-table-column>
                <el-table-column prop="inventoryQuantity" label="库存数量" min-width="200">
                </el-table-column>
                 <el-table-column prop="returnQuantity" label="本次退货数量" min-width="200">
                    <template slot-scope="{ row, $index }">
                    <el-input
                    v-enter-float2="{
                              set: row,
                              key: 'returnQuantity'
                          }"
                      @input="input(row)"
                      @blur="returnQuantity"
                      v-model="row.returnQuantity"
                      clearable
                      v-if="$index > 0&& row.billId"
                    ></el-input>
                  </template>
                </el-table-column>
                 <el-table-column prop="previousTotalReturnQuantity" label="截止上期末退货数量" min-width="200">
                </el-table-column>
                 <el-table-column prop="currentTotalReturnQuantity" label="截止本期末退货数量" min-width="200">
                </el-table-column>
              </el-table>
            </div>
          </div>

          <!-- 附件信息 -->
                <div id="accessoryCon" class="con">
                    <div class="tabs-title" id="accessory">附件信息</div>
                    <attach-comp :relationId="attachId" bucketName="material"  v-if="objFlag.flag5"/>
                    <div class="seize-a-seat" v-else>
                        <i class="el-icon-loading"></i>
                    </div>
                </div>

          <!-- 审核历史 -->
           <div id="auditHistoryCon" class="con">
            <div class="tabs-title" id="auditHistory">审核历史</div>
            <div class="e-table">
              <ComAuditHistoryIndex
                :tableData.sync="auditHistoryTable"
                @getAuditHistory="getAuditHistory"
                ref="AuditHistoryRef"
              />
            </div>
          </div>
        </div>
      </el-tabs>
    </div>
    <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
    <div class="buttons">
        <span class="tip"
        ><span style="color: red; margin-right: 0">*</span>为必填项</span
      >
      <el-button
          type="primary"
          style="background: #2e61d7"
          v-debounce
          v-if="basicFormData.state === '1'"
          >打印</el-button
      >
       <ComExaButtons
                v-if="basicFormData.state != 5"
                :auditState="auditState"
                :state="basicFormData.state"
                 :founderId="founderId"
                @exas="exas"
            />

      <!-- <el-button
        type="primary"
        style="background: #2e61d7"
        @click="save()"
        v-debounce
        >保存</el-button
      >
      <el-button
        type="primary"
        style="background: #2e61d7"
        @click="submit()"
        v-debounce
        >保存并提交</el-button
      >
      <el-button
        type="primary"
        style="background: #2e61d7"
        v-debounce
        v-if="basicFormData.state === '1'"
        @click="undoAudit"
        >撤回</el-button
      >
      <el-button
        type="primary"
        class="btn-delete"
        v-debounce
        v-if="basicFormData.state === '1'"
        @click="nullify()"
        >作废</el-button
          >

     <el-button
        type="danger"
        size="small"
        @click="ctDelete"
        class="btn-delete"
        v-if="basicFormData.state === '0'"
        v-debounce
        >删除</el-button
      > -->
      <el-button @click="cancel()">关闭</el-button>
    </div>
  </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import { mapMutations, mapState } from 'vuex'
import AttachComp from '@/components/common/attachIndex'
import CommonApi from '@/api/materials/common.js'
import Api from '@/api/materials/supplierRetreat.js'
import {  getUuid, selectDataClient, openAppClient, getItem } from '@/utils/common'
import ComAuditHistoryIndex from '@/pages/materialsmanagement/components/auditHistory/auditHistoryIndex'
import subcontractorRAP from '@/api/OutsourcingartyAdmin/subcontractorAdmin/subcontractorRAP.js'
export default {
    data () {
        return {
            tabsName: 'baseInfo',
            userName: '',
            form: {
                name: '',
                region: '',
                date1: '',
                date2: '',
                delivery: false,
                type: [],
                resource: '',
                desc: '',
            },
            isBatch: true,
            auditState: {}, //按钮状态

            iswuzi: false,
            tableData: [],
            errorList: [], //控制导航栏感叹号的显示
            errorMsg: [],
            isErrorMsg: true, //是否提醒错误信息
            auditHistoryTable: [], //审核历史
            receivingList: [], //明细
            value: '',
            textarea: '',
            formData: {},
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            //基本信息表单数据
            basicFormData: {
                'billId': '',
                'billNo': '',
                'currentTotalReturnQuantity': 0,
                'evaluationId': '',
                'evaluationLevel': '',
                'founderId': '',
                'founderName': '',
                'gmtCreate': '',
                'gmtModified': '',
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': '',
                'orgId': '',
                'orgName': '',
                'previousTotalReturnQuantity': 0,
                'receivedQuantity': 0,
                'receivingPersonnelId': '',
                'receivingPersonnelName': '',
                'remarks': '',
                'returnDate': '',
                'returnQuantity': 0,
                'state': '',
                'supplierId': '',
                'supplierName': '',
                'warehouseKeeperId': '',
                'warehouseKeeperName': '',
                'workId': ''
            },
            objFlag: {
                flag5: false,
            },
            auditParams: {
                billId: this.$route.query.billid, //单据Id  ***
                billType: '1007', //单据编码  ***
                dtls: [], //审核中字段值变更历史
                freeNextUnitIndex: 0, //下一步审核步骤
                freeNextUser: '', //下一步审核人ID
                isPass: true, //审核是否通过
                isShareInAudit: true, //是否共享审核节点
                opinion: '', //审核意见   ***
                orgId: JSON.parse(localStorage.getItem('vuex')).userInfo.orgInfo.orgId, //单据机构Id
                orgName: JSON.parse(localStorage.getItem('vuex')).userInfo.orgInfo.orgName, //单据机构名称
                userId: localStorage.getItem('userId'), //审核人Id    ***
                workId: '', //流程Id
            },
            nullifyParams: { //作废
                'billId': this.$route.query.billid,
                'billType': 1007,
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': ''
            },

            orgId: '', //机构id
            orgName: '', //机构名称
            userList: [], //接收人员数据
            userLists: [], //库管人员数据
            isSkip: false, //是否跳转
            otherbasicFormData: {},
            //验证
            rules: {
                returnDate: [
                    { required: true, message: '请选择退货日期', trigger: 'change' }
                ],
                receivingPersonnelName: [
                    { required: true, message: '请选择接收人员', trigger: 'change' }
                ],
                warehouseKeeperName: [
                    { required: true, message: '请选择库管人员', trigger: 'change' }
                ],
                evaluationLevel: [
                    { required: true, message: '请进行评价', trigger: 'change' }
                ],
            }
        }
    },
    computed: {
        ...mapState({
            options: state => state.contract.ctClassify,
        }),
        judgeRoute () {
            if (this.$route.path.includes('Add')) {
                return false
            }
            return true
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        },
        attachId () {
            return this.billid
        }
    },
    watch: {
        //给错误标签加上提醒
        errorList: newData => {
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM => {
                const { childNodes } = DOM
                if (childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item => {
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        },

    },
    components: {
        AttachComp,
        ComAuditHistoryIndex,
    },
    created () {

        let data = JSON.parse(localStorage.getItem('vuex'))
        this.orgId = data.userInfo.orgInfo.orgId
        this.orgName = data.userInfo.orgInfo.orgName
        this.userId = localStorage.getItem('userId')
        this.founderId = localStorage.getItem('userId')

        this.userName = localStorage.getItem('userName')
        this.basicFormData.receivingPersonnelName = localStorage.getItem('userName')
        this.basicFormData.warehouseKeeperName = localStorage.getItem('userName')
        this.billid = this.$route.query.billid
        this.getuser()
        this.getBasicData()
        this.getAttach()
        this.getMasterPlan()
        this.getCurrentUnitInfo()

    },
    mounted () {
    // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = ['baseInfo', 'receivingMaterials', 'accessory', 'auditHistory']
        this.tabArr = arr //标星星
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const $item = document.getElementById(item)
                    let itemTop = null
                    if ($item) {
                        itemTop = $item.offsetTop
                    }
                    return itemTop
                })
            }
            const scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if (scrollTop + 1 >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })
        this.scorllDtl()
    },
    methods: {

        ...mapMutations(['setSelectedInfo', 'setAuditParams']),
        // 获取按钮状态
        getCurrentUnitInfo () {
            CommonApi
                .getCurrentUnitInfo({
                    billId: this.$route.query.billid,
                    billType: 1007,
                    freeNextUnitIndex: 0,
                    freeNextUser: '',
                    isPass: true,
                    isShareInAudit: true,
                    opinion: ''
                })
                .then(res => {
                    this.auditState = res
                })
        },
        // 按钮组件触发事件
        exas (data) {
            switch (data) {
            case 'audit':
                this.audit() //审核
                break
            case 'undoAudit':
                this.undoAudit() //撤回
                break
            case 'submitCommit':
                this.submit() //提交
                break
            case 'submit':
                this.save() //保存
                break
            case 'nullify':
                this.nullify() //作废
                break
            case 'deleteData':
                this.ctDelete() //删除
                break
            default:
                break
            }
        },
        //作废
        nullify () {
            this.setAuditParams(this.nullifyParams)
            openAppClient('/nullifyDialog', '单据作废原因', () => {
                const auditParams = JSON.parse(localStorage.vuex).auditParams
                CommonApi.nullify(auditParams).then(() => {
                    this.clientPop('suc', '作废成功', this.cancel, null, this.cancel)
                })
            })
        },
        //撤回
        undoAudit () {
            const params2 = {
                billId: this.billid, //单据Id  ***
                billType: '1007', //单据编码  ***
                dtls: [], //审核中字段值变更历史
                freeNextUnitIndex: 0, //下一步审核步骤
                freeNextUser: '', //下一步审核人ID
                isPass: true, //审核是否通过
                isShareInAudit: true, //是否共享审核节点
                opinion: '', //审核意见   ***
                orgId: '', //单据机构Id
                orgName: '', //单据机构名称
                userId: this.userId, //审核人Id    ***
                workId: '', //流程Id
            }
            CommonApi.undoAudit(params2).then(() => {
                this.clientPop('suc', '撤回成功！', this.cancel, null, this.cancel)
            })
        },

        //汇总收料数量
        totalreceivedQuantity () {
            let num = 0
            this.receivingList.forEach(a=>{
                a.children.forEach(item=>{
                    num += Number(item.inventoryQuantity)
                })
            })
            this.basicFormData.receivedQuantity = num
        },
        //计算基础信息本期末退货数量   截止上期退货数量+退货数量
        totalcurrentTotalReturnQuantity () {
            this.basicFormData.currentTotalReturnQuantity = this.basicFormData.previousTotalReturnQuantity + this.basicFormData.returnQuantity
        },
        //计算上期末退货数量
        totalpreviousTotalReturnQuantity () {
            let num = 0
            this.receivingList.forEach(a=>{
                a.children.forEach((item, i)=>{
                    if(i > 0) {
                        num += Number(item.currentTotalReturnQuantity)
                        // item.currentTotalReturnQuantity = Number(item.previousTotalReturnQuantity) + Number(item.returnQuantity)

                    }
                    item.previousTotalReturnQuantity = num
                })
            })
            // this.totalcurrentTotalReturnQuantity()

        },
        //计算本期末退货数量
        totalcurrentTotalReturnQuantityList () {
            this.receivingList.forEach(a=>{
                a.children.forEach(item=>{
                    item.currentTotalReturnQuantity = Number(item.previousTotalReturnQuantity) + Number(item.returnQuantity)
                })
            })
        },
        //跳转到明细
        scorllDtl () {
            if(this.$route.query.name) {
                setTimeout(() => {
                    //因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                    let obj = {
                        name: this.$route.query.name
                    }
                    this.tabsName = this.$route.query.name
                    this.onChangeTab(obj)
                }, 200)
            }
        },
        //去供应商评价页面
        evaluate () {
            let id = this.basicFormData.supplierId
            let type = 11
            openAppClient(`/otherDynamicEvaluate?supplierId=${id}&type=${type}&source=${1}&billid=${this.billid}`, '退货评价',    async ()=> {
                const otherbasicFormData =  getItem('basicFormData')//获取值
                const otherbasicFormData1 =  JSON.parse(getItem('evaluationItems'))//获取值
                this.basicFormData.evaluationLevel = otherbasicFormData1.complexEvaluate
                if(otherbasicFormData1.complexEvaluate == 4) {
                    this.basicFormData.evaluationLevel = 'D'
                }else if(otherbasicFormData1.complexEvaluate > 60 && otherbasicFormData1.complexEvaluate <= 75 ) {
                    this.basicFormData.evaluationLevel = 'C'
                }else if(otherbasicFormData1.complexEvaluate > 75 && otherbasicFormData1.complexEvaluate <= 89) {
                    this.basicFormData.evaluationLevel = 'B'
                }else {
                    this.basicFormData.evaluationLevel = 'A'
                }
                otherbasicFormData1.id = this.billid
                otherbasicFormData1.creditRatingTemplateDtls.map(item => {
                    if (item.children) {
                        item.children.map(newItem => {
                            newItem.id = this.billid
                        })
                    }
                    item.id = this.billid
                })
                //保存 基本信息
                await subcontractorRAP
                    .annualEvaluationUpdate(otherbasicFormData).catch(()=>{
                        this.basicFormData.evaluationLevel = ''
                    })

                //明细
                await subcontractorRAP
                    .AddannualEvaluationDetailed(otherbasicFormData1).catch(()=>{
                        this.basicFormData.evaluationLevel = ''
                    })

            })

        },
        //汇总 退货数量
        returnQuantity () {
            //汇总退货明细中所有物资的本次退货数量 returnQuantity  上期末 previousTotalReturnQuantity  本期末 currentTotalReturnQuantity
            let num = 0
            let num1 = 0
            this.receivingList.forEach(a=>{
                a.children.forEach(b=>{
                    num = Number(b.returnQuantity) + num
                    b.currentTotalReturnQuantity = Number(b.previousTotalReturnQuantity) +  Number(b.returnQuantity)
                    num1 += Number(b.returnQuantity)
                    a.materialName = `小计:${num1}`
                    // if(index > 0) {
                    //     b.previousTotalReturnQuantity += Number(b.currentTotalReturnQuantity)
                    // }
                })
            })
            this.basicFormData.returnQuantity = num
            this.totalcurrentTotalReturnQuantity()

            // this.receivingList.forEach(c=>{
            //     c.children.forEach((d, index)=>{
            //         if(index > 0) {
            //             d.previousTotalReturnQuantity = d.currentTotalReturnQuantity - d.previousTotalReturnQuantity
            //         }
            //     })
            // })

        },

        getuser () {
            this.$Ajax
                .httpGet({
                    url: '/hr/user/getUserUnderOrg',
                    params: {
                        orgId: this.orgId,
                    },
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                })
                .then(res => {
                    this.userList = res
                    this.userLists = res
                })
        },
        //获取基本信息数据
        getBasicData () {
            this.$Ajax
                .httpGet({
                    url: '/material/supplierReturn/findById',
                    params: {
                        id: this.billid,
                    },
                })
                .then(res => {
                    // this.basicFormData = res
                    for(let key in res) {
                        this.basicFormData[key] = res[key]
                    }
                })
        },
        //获取明细数据
        getMasterPlan () {
            this.$Ajax
                .httpGet({
                    url: '/material/supplierReturn/getListById',
                    params: {
                        id: this.billid,
                    },
                })
                .then(res => {
                    res.forEach(item => {
                        item.materialClassName = item.topClassName
                        item.uuid = getUuid()
                        item.children.forEach(i => {
                            i.uuid = i.dtlId
                        })
                        const count = item.children.reduce(
                            (prev, c) => (prev += Number(c.inventoryQuantity) || 0),
                            0
                        )
                        item.materialName = `小计： ${count}`
                    })
                    this.receivingList = res
                })
        },
        //选择库存
        selectMaterial () {
            let ids = []
            let warehouseType = 0
            selectDataClient({
                SelectServiceToken: '/material/stock/listUsableInventoryByOrgIdForSelect', // 客户端对应方法名
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                InitParamsStr: JSON.stringify(warehouseType),    // 接口参数(name为模拟参数)
                Title: '选择库存明细' // 标题
            }).then(val=>{
                this.setSelectedInfo(val)
                //     openAppClient('/showSelectedData', '选择结果', function () {
                //         // alert('关闭后回调')
                //     })
                // let val = [{ 'billId': '1569137878269358081', 'id': '1570700732273455106', 'isDetailed': 1, 'lockedQuantity': 0, 'materialClassId': 'a92724915394-8f4a-2247-3575-754cb0ea/8366c07b-9a82-4a80-9626-337b2a76a1af/10b8c980-981b-4e90-81b8-550288428a04', 'materialClassName': '其它材料/木材/胶合板', 'materialId': 'a99820331b56-a7a8-0247-4367-1e3a71f7', 'materialName': '胶合板', 'parentId': '000d3773-21d6-44bf-8c80-ae1d420fdc38', 'partyAType': null, 'quantity': 40, 'sourceId': '1569136855492521985', 'sourceName': null, 'sourceNo': 'SRBGEHGSL204LXCGJH20220912001', 'sourceType': '0', 'spec': null, 'stockType': '1', 'subcontractorId': '000d3773-21d6-44bf-8c80-ae1d420fdc38', 'subcontractorName': '成都三和智造科技有限公司', 'texture': null, 'unit': '㎡', 'warehouseId': '1561908689212469249', 'warehouseName': '项目部仓库' }]
                if(this.receivingList.length > 0) {
                    val.forEach(e=>{
                        if(this.basicFormData.supplierId != e.subcontractorId) {
                            this.clientPop('info', '请选择同一家供应商/加工单位物资')
                        }else{

                            this.basicFormData.supplierId  = e.subcontractorId
                            this.basicFormData.supplierName  = e.subcontractorName
                            e.materialClassNameArr = e.materialClassName.split('/')
                            e.materialClassIdArr = e.materialClassId.split('/')
                            e.materialClassNameArr.shift()
                            e.materialClassIdArr.shift()
                            const obj = {
                                uuid: getUuid(),
                                customId: getUuid(),
                                'billId': this.billid,
                                'changeType': 1,
                                'dtlId': '',
                                'inventoryQuantity': e.quantity, //存库数量
                                'materialClassId': e.materialClassIdArr.join('/'),
                                'materialClassName': e.materialClassNameArr.join('/'),
                                'materialId': e.materialId,
                                'materialName': e.materialName,
                                'returnQuantity': e.quantity, //本次退货数量
                                'spec': e.spec,
                                'previousTotalReturnQuantity': 0,
                                'texture': e.texture,
                                'unit': e.unit,
                                'warehouseId': e.warehouseId,
                                'warehouseName': e.warehouseName,
                                'sourceId': e.sourceId, //库存源单id
                                'sourceName': e.sourceName, //库存源单名称
                                'sourceNo': e.sourceNo, //库存源单编号
                                'sourceType': e.sourceType, //库存源单类型
                            }
                            this.receivingList.forEach(item=>{
                                item.children.push(obj)
                            })
                            this.getSupplierReturnPreviousTotalInfo(e)
                        }

                    })
                }else{

                    const mapObj = {}
                    let arr = []
                    val.forEach(b => {
                    // this.basicFormData.receivedQuantity = b.quantity  // 基础信息收料数量
                        this.basicFormData.supplierId  = b.subcontractorId
                        this.basicFormData.supplierName  = b.subcontractorName
                        const children = []
                        this.basicFormData.sourceId = b.billId
                        this.basicFormData.sourceNumber = b.billNo
                        b.materialClassNameArr = b.materialClassName.split('/')
                        b.materialClassIdArr = b.materialClassId.split('/')
                        // TODO: 统计小计
                        let obj
                        const topClassId = b.materialClassIdArr.splice(0, 1).toString()
                        const topClassName = b.materialClassNameArr.splice(0, 1).toString()
                        if (!mapObj[topClassId]) {
                            obj = {
                                topClassId,
                                topClassName,
                                customId: topClassId,
                                materialClassId: topClassId,
                                materialClassName: topClassName,
                                uuid: getUuid(),
                                totalAmount: null,
                                totalQuantity: null,
                            }
                            //这里需要改成push多个对象   还没改
                            arr.push(obj)
                            mapObj[topClassId] = obj
                        } else {
                            obj = mapObj[topClassId]
                        }
                        // 物资名称
                        children.push({
                            uuid: getUuid(),
                            customId: getUuid(),
                            'billId': this.billid,
                            'changeType': 1,
                            'dtlId': '',
                            'inventoryQuantity': b.quantity, //存库数量
                            'materialClassId': b.materialClassIdArr.join('/'),
                            'materialClassName': b.materialClassNameArr.join('/'),
                            'materialId': b.materialId,
                            'materialName': b.materialName,
                            'returnQuantity': b.quantity, //本次退货数量
                            'spec': b.spec,
                            'previousTotalReturnQuantity': 0,
                            'texture': b.texture,
                            'unit': b.unit,
                            'warehouseId': b.warehouseId,
                            'warehouseName': b.warehouseName,
                            'sourceId': b.sourceId, //库存源单id
                            'sourceName': b.sourceName, //库存源单名称
                            'sourceNo': b.sourceNo, //库存源单编号
                            'sourceType': b.sourceType, //库存源单类型
                        })
                        obj.children = !obj.children
                            ? children
                            : obj.children.concat(children)
                        // 统计小计
                        const count = obj.children.reduce(
                            (prev, c) => (prev += Number(c.returnQuantity) || 0),
                            0
                        )
                        obj.materialName = `小计： ${count}`
                        obj.children = this.uniqueArray(obj.children, 'customId')

                        this.getSupplierReturnPreviousTotalInfo(b)
                    })
                    this.receivingList = arr
                }

                this.returnQuantity()
                this.totalreceivedQuantity()
                this.issource()
                // this.totalpreviousTotalReturnQuantity()
                this.totalcurrentTotalReturnQuantityList()
            })

        },
        //判断源单来源
        issource () {
            this.receivingList.forEach(a=>{
                const val =  a.children.some(item=>{return item.sourceType == '1'})
                if(val) {
                    this.iswuzi = true
                }
            })
        },
        //获取上期末退货数量
        getSupplierReturnPreviousTotalInfo (e) {
            const params = {
                dtls: [],
                orgId: this.orgId,
                supplierId: this.basicFormData.supplierId,
            }
            const obj = {
                'materialClassId': e.materialClassId,
                'materialId': e.materialId,
                'quantity': 0,
                'spec': e.spec,
                'texture': e.texture,
                'unit': e.unit,
                'warehouseId': e.warehouseId
            }
            params.dtls.push(obj)

            Api.getSupplierReturnPreviousTotalInfo(params).then(res=>{
                console.log('res', res)
                if(res.dtls) {
                    res.dtls.forEach(item=>{
                        item.materialClassIdOne = item.materialClassId.split('/')
                        item.materialClassIdOne = item.materialClassIdOne.splice(0, 1).toString()
                        item.materialClassId = item.materialClassId.split('/')
                        item.materialClassId = item.materialClassId.splice(1, 2)
                        item.materialClassId = item.materialClassId.join('/')
                        this.receivingList.forEach(a=>{
                            a.children.forEach(b=>{
                                if(item.materialClassIdOne === a.materialClassId && item.materialClassId === b.materialClassId && item.materialId === b.materialId && item.spec === b.spec && item.texture === b.texture && item.unit === b.unit && item.warehouseId === b.warehouseId) {
                                    b.previousTotalReturnQuantity = res.quantity
                                    b.currentTotalReturnQuantity =  b.previousTotalReturnQuantity + b.returnQuantity
                                    this.basicFormData.previousTotalReturnQuantity = res.quantity
                                    this.totalcurrentTotalReturnQuantity()

                                }

                            })
                        })

                    })
                }
            })
        },
        count_ (obj) {
            return obj.children.reduce((prev, c) => (prev += c.amount || 0), 0)
        },
        //明细数据汇总方法
        uniqueArray (arr, key) {
            const map = new Map()
            return arr.filter(item => {
                const val = item[key] + '' || getUuid()
                return !map.has(val) && map.set(val, 1)
            })
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('evaluateCon')) {
                    const lastConHeight =
            document.getElementById('evaluateCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    console.log('this.lastConHeight', this.lastConHeight)
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        //查询附件信息
        getAttach () {
            this.objFlag.flag5 = true
        },
        //删除物资明细
        deleteEle (row) {
            row.changeType = -1
        },
        tableRowClassName ({ row }) {
            if (row.changeType === -1) {
                return 'warning-row'
            }
            return ''
        },
        //监听明细数据input事件
        input (row) {
            if(row.changeType === 1) {
                row.changeType = 1
            }else {
                row.changeType = 2
            }
            if(row.returnQuantity > row.inventoryQuantity) {
                this.clientPop(
                    'err',
                    '本次退货数量不能超过库存数量!',
                )
                setTimeout(()=>{
                    row.returnQuantity = row.inventoryQuantity

                })

            }
        },

        //保存
        save () {
            this.errorList = []
            this.verifyTable()
            Promise.all([this.updateBaseInfo(), this.updateBudgetDtl()])
                .then(() => {
                    this.clientPop('suc', '保存成功', this.$router.go(0))
                })
                .catch(() => {
                    this.scorllError()
                })
        },
        //保存并提交
        submit () {
            this.errorList = []
            this.verifyTable()
            Promise.all([this.updateBaseInfo(), this.updateBudgetDtl()])
                .then(() => {
                    CommonApi.AuditCommit(this.auditParams).then(() => {
                        this.clientPop('suc', '保存并提交成功', this.cancel, null, this.cancel)
                    })
                })
                .catch(() => {
                    this.scorllError()
                })

        },
        //更新基本信息
        updateBaseInfo () {
            return new Promise((resolve, reject) => {
                this.verifyTable()
                    .then(() => {
                        Api.EditSupplierRetreat(this.basicFormData)
                        this.getBasicData() //更新基本信息
                        resolve()
                    })
                    .catch(err => {
                        this.setError('baseInfo')
                        reject(err)
                    })

            })
        },

        //更新计划明细
        updateBudgetDtl () {
            return new Promise((resolve, reject) => {
                this.verifyTable()
                    .then(() => {
                        Api.EditSupplierRetreatList(this.receivingList)
                            .then(() => {
                                resolve()
                            })
                            .catch(err => {
                                this.setError('receivingMaterials')
                                reject(err)
                            })
                    })
                    .catch(err => {
                        this.setError('receivingMaterials')
                        reject(err)
                    })
            })
        },
        ctDelete () {
            this.clientPop(
                'info',
                '确定要删除吗？删除的数据可以在【回收站】还原或彻底删除。',
                this.delData
            )
        },
        //明细非空验证
        verifyTable () {
            return new Promise((resolve, reject) => {
                this.errorMsg = []
                if(this.receivingList.length === 0) {
                    let str = '退货明细不能为空！'
                    this.errorMsg.push(str)
                }
                else  if (this.receivingList.length > 0) {
                    this.receivingList.forEach(v => {
                        v.children.forEach((item, index) => {
                            if (item.changeType !== -1) {
                                if (item.returnQuantity === '' || item.returnQuantity === null) {
                                    let str = `请填写第 ${index + 1} 行的本次退货数量`
                                    this.errorMsg.push(str)
                                }
                                if(item.sourceType == '1') {
                                    if(this.basicFormData.evaluationLevel === '' ||  this.basicFormData.evaluationLevel === null) {
                                        let str = '请在基本信息对合同类的供应商进行退货评价!'
                                        this.errorMsg.push(str)
                                    }
                                }

                            }
                            // if(this.basicFormData.evaluationLevel === '' ||  this.basicFormData.evaluationLevel === null) {
                            //     this.errorMsg.push('')
                            // }
                        })
                    })
                }

                if (this.errorMsg.length > 0) {
                    this.isErrorMsg = true
                    reject()
                } else {
                    this.isErrorMsg = false
                    resolve()
                }
            })
        },
        setError (name) {
            if (!this.errorList.find(x => x === name)) {
                this.errorList.push(name)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item => {
                let index = this.tabArr.findIndex(x => x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },

        //删除
        delData () {
            this.$Ajax
                .httpGet({
                    url: '/material/supplierReturn/delete',
                    params: {
                        id: this.billid,
                    },
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                })
                .then(res => {
                    if (res.code == 200) {
                        this.clientPop('suc', '删除成功', this.cancel, null, this.cancel)
                    }
                })
        },
        //获取历史审核列表
        getAuditHistory () {
            const params = {
                billId: this.billid,
                billType: '1007',
                freeNextUnitIndex: 0,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: '',
                orgId: '',
                orgName: '',
                userId: '',
                workId: '',
            }
            CommonApi.getAuditHistory(params).then(res => {
                this.auditHistoryTable = res
            })
        },
        handleFullScreen () {
            this.fullscreen = !this.fullscreen
        },
        //关闭
        cancel () {
            this.dialogVisible = false
            this.$router.replace('./supplierRetreat')
        },
        cellClsNm ({ column }) {
            if (column.label === '') {
                return 'fixed-left'
            }
        },

        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
    },
}
</script>

<style lang="scss" scoped>
.buttons {
  left: 0;
}
.e-form {
  margin-bottom: 80px;
  padding: 0 20px;
  .tabs-title::before {
    content: "";
    height: 22px;
    width: 8px;
    border-radius: 40px;
    background-color: #2e61d7;
    display: block;
    position: absolute;
    left: 20px;
    margin-right: 20px;
  }
}

.e-table {
  background: #fff;
}
::v-deep.el-table .warning-row {
  display: none;
}
// ::v-deep.el-table__body-wrapper::-webkit-scrollbar{
//      width: 6px !important; // 横向滚动条
//     height: 10px !important// 纵向滚动条
// }

::v-deep .el-table__body-wrapper::-webkit-scrollbar {
  width: 6px; // 横向滚动条
  height: 10px; // 纵向滚动条
}
// 滚动条的滑块
::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
  background-color: #ddd;
  border-radius: 5px;
}

.el-tab-pane {
  margin-left: -10px;
}

</style>